import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 18. 四数之和
 */
public class No18 {
    public static void main(String[] args) {
        System.out.println(fourSum(new int[]{1000000000, 1000000000, 1000000000, 1000000000}, -294967296));
    }

    public static List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> lists = new ArrayList<>();
        for (int i = 0; i < nums.length - 3; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < nums.length - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                int k = j + 1, l = nums.length - 1;
                while (k < l) {
                    long res = (long) nums[i] + nums[j] + nums[k] + nums[l];
                    if (res == target) {
                        lists.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));
                        do {
                            k++;
                        } while (nums[k] == nums[k - 1] && k < l);
                        do {
                            l--;
                        } while (nums[l] == nums[l + 1] && k < l);
                    } else if (nums[k] + nums[l] < target - (nums[i] + nums[j])) {
                        k++;
                    } else {
                        l--;
                    }
                }
            }
        }
        return lists;
    }
}
